package com.orm;

//import android.database.sqlite.SQLiteDatabase;
//import android.database.sqlite.SQLiteOpenHelper;

import net.sqlcipher.database.SQLiteDatabase;
import net.sqlcipher.database.SQLiteException;
import net.sqlcipher.database.SQLiteOpenHelper;

import android.content.Context;
import android.util.Log;

import com.base.common.app.BaseConstant;
import com.base.data.BuildConfig;
import com.orm.helper.ManifestHelper;
//import com.orm.util.SugarCursorFactory;

import java.io.File;
import java.io.IOException;

import static com.orm.util.ContextUtil.getContext;
import static com.orm.helper.ManifestHelper.getDatabaseVersion;
import static com.orm.helper.ManifestHelper.getDbName;
import static com.orm.SugarContext.getDbConfiguration;

public class SugarDb extends SQLiteOpenHelper {
    private static final String LOG_TAG = "Sugar";

    private final SchemaGenerator schemaGenerator;
    private SQLiteDatabase sqLiteDatabase;
    private int openedConnections = 0;
    private static final String DB_PWD = BaseConstant.DATABASE_PASSWORD; //数据库密码

    //Prevent instantiation
    private SugarDb() {
//        super(getContext(), getDbName(), new SugarCursorFactory(ManifestHelper.isDebugEnabled()), getDatabaseVersion());
        super(getContext(), getDbName(), null, getDatabaseVersion());
        schemaGenerator = SchemaGenerator.getInstance();
        //不可忽略的 进行so库加载
        SQLiteDatabase.loadLibs(getContext());

        try {
            getDB();
        } catch (SQLiteException e) {
            try {
                //如果有导入的未加密数据库，则加密
                encrypt(getContext(), getDbName(), DB_PWD);
            } catch (SQLiteException|IOException e1) {
                e1.printStackTrace();
            }
        }


    }

    public static SugarDb getInstance() {
        return new SugarDb();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        schemaGenerator.createDatabase(db);
        final SugarDbConfiguration configuration = getDbConfiguration();

        if (null != configuration) {
            db.setLocale(configuration.getDatabaseLocale());
            db.setMaximumSize(configuration.getMaxSize());
            db.setPageSize(configuration.getPageSize());
        }
    }

//    @Override
//    public void onConfigure(SQLiteDatabase db) {
//        final SugarDbConfiguration configuration = getDbConfiguration();
//
//        if (null != configuration) {
//            db.setLocale(configuration.getDatabaseLocale());
//            db.setMaximumSize(configuration.getMaxSize());
//            db.setPageSize(configuration.getPageSize());
//        }
//
//        super.onConfigure(db);
//    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        schemaGenerator.doUpgrade(sqLiteDatabase, oldVersion, newVersion);
    }

    public synchronized SQLiteDatabase getDB() {
        if (this.sqLiteDatabase == null) {
            this.sqLiteDatabase = getWritableDatabase(DB_PWD);
        }

        return this.sqLiteDatabase;
    }

    //    @Override
    public synchronized SQLiteDatabase getReadableDatabase() {
        if (ManifestHelper.isDebugEnabled()) {
            Log.d(LOG_TAG, "getReadableDatabase");
        }
        openedConnections++;
        return super.getReadableDatabase(DB_PWD);
    }

    @Override
    public synchronized void close() {
        if (ManifestHelper.isDebugEnabled()) {
            Log.d(LOG_TAG, "getReadableDatabase");
        }
        openedConnections--;
        if (openedConnections == 0) {
            if (ManifestHelper.isDebugEnabled()) {
                Log.d(LOG_TAG, "closing");
            }
            super.close();
        }
    }

    /**
     * 对未加密的数据加密
     *
     * @param context
     * @param dbName
     * @param passphrase
     * @throws IOException
     */
    public static void encrypt(Context context, String dbName, String passphrase) throws IOException {

        File originalFile = context.getDatabasePath(dbName);

        if (originalFile.exists()) {

            File newFile = File.createTempFile("sqlcipherutils", "tmp", context.getCacheDir());

            SQLiteDatabase db = SQLiteDatabase.openDatabase(originalFile.getAbsolutePath(), "", null, SQLiteDatabase.OPEN_READWRITE);

            db.rawExecSQL(String.format("ATTACH DATABASE '%s' AS encrypted KEY '%s';", newFile.getAbsolutePath(), passphrase));

            db.rawExecSQL("SELECT sqlcipher_export('encrypted')");

            db.rawExecSQL("DETACH DATABASE encrypted;");

            int version = db.getVersion();

            db.close();

            db = SQLiteDatabase.openDatabase(newFile.getAbsolutePath(), passphrase, null, SQLiteDatabase.OPEN_READWRITE);

            db.setVersion(version);

            db.close();

            originalFile.delete();

            newFile.renameTo(originalFile);

        }

    }
}
